package com.wwd.movie.common.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.region.Region;
import com.wwd.movie.common.config.TencentCosConfig;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
public class TencentCosUtil {

    private final TencentCosConfig cosConfig;

    public TencentCosUtil(TencentCosConfig cosConfig) {
        this.cosConfig = cosConfig;
    }

    /**
     * 创建 COS 客户端
     */
    private COSClient createClient() {
        COSCredentials cred = new BasicCOSCredentials(
                cosConfig.getSecretId(),
                cosConfig.getSecretKey()
        );
        ClientConfig clientConfig = new ClientConfig(new Region(cosConfig.getRegion()));
        return new COSClient(cred, clientConfig);
    }

    /**
     * 上传文件（默认 upload/ 路径，UUID 文件名）
     */
    public String upload(MultipartFile file) throws Exception {
        return upload(file, "upload/");
    }

    /**
     * 上传文件（自定义路径，UUID 文件名）
     */
    public String upload(MultipartFile file, String path) throws Exception {
        // 使用原始文件后缀
        String originalName = file.getOriginalFilename();
        String suffix = "";
        if (originalName != null && originalName.contains(".")) {
            suffix = originalName.substring(originalName.lastIndexOf("."));
        }
        String fileName = UUID.randomUUID() + suffix;
        return upload(file, path, fileName);
    }

    /**
     * 上传文件（自定义路径 + 自定义文件名）
     * @param file     文件
     * @param path     路径前缀，例如 "avatar/"、"video/"
     * @param fileName 文件名（可带后缀）
     * @return 文件访问 URL
     */
    public String upload(MultipartFile file, String path, String fileName) throws Exception {
        COSClient cosClient = createClient();
        try (InputStream inputStream = file.getInputStream()) {
            // 拼接路径（确保以 / 结尾）
            if (!path.endsWith("/")) {
                path += "/";
            }
            String key = path + fileName;

            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(file.getSize());
            metadata.setContentType(file.getContentType());

            cosClient.putObject(cosConfig.getBucket(), key, inputStream, metadata);

            return "https://" + cosConfig.getBucket() +
                    ".cos." + cosConfig.getRegion() +
                    ".myqcloud.com/" + key;
        } finally {
            cosClient.shutdown();
        }
    }
}
